<template>
	<div class="article-manager video-icon form-submit" id="shopp-manager">
		<Modal v-model="innerVisible" :title="$t('page.product.add')" :width="900" @on-ok="handleOk" @on-cancel="handleClose">
			<Form ref="formDynamic" :model="formDynamic" class="attrFrom" @submit.native.prevent>
				<Row :gutter="24">

					<Col span="24">
					<a @click="addProduct()" size="small"><Button type="primary"
							icon="ios-add-circle-outline">{{$t('page.order.add')}}
							{{$t('page.order.item')}}</Button></a>
					</Col>
					<Col span="24">
					
					<h3 style="margin-top: 20px;line-height: 30px;">{{$t('page.activity.information')}}</h3>
					<Table border :columns="goodsColumns" :data="[radioProduct]">

						<template slot="image" slot-scope="{ row }">
						    <viewer>
						      <div class="tabBox_img">
						        <img v-lazy="row.image" width="60" />
						      </div>
						    </viewer>
						  </template>
					</Table>
					<h3 style="margin-top: 20px;line-height: 30px;">{{$t('page.activity.configure')}} ({{ radioProduct.store_name }})</h3>
					<Table border :columns="skuColumns" :data="radioProduct.skuList" editable max-height="500">
				
						<template slot="activity_price" slot-scope="{ row, index }">
						    <Input
						      :value="radioProduct.skuList[index].activity_price"
						      :placeholder="$t('page.activity.event_price')"
						      @input="val => radioProduct.skuList[index].activity_price = val"
							  :disabled="radioProduct.skuList[index].stock == 0"
						    />
						</template>
						<template slot="warehouse" slot-scope="{ row, index }">
						    <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
						                {{warehouse.warehouse}}
						                <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
						              </div>
						</template>
						<template slot="stock" slot-scope="{ row, index }">
						    <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
						                <Input
						                  :value="warehouse.stock"
						                  disabled
						                />
						                <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
						              </div>
						</template>
						<template slot="activity_stock" slot-scope="{ row, index }">
						  <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
						    <Input
						      :value="getActivityStockValue(row, wIndex)"
						      :placeholder="$t('page.activity.event_stock')"
						      @input="val => handleStockInput(val, index, wIndex)"
						      :disabled="warehouse.stock == 0"
						      type="number"
						      min="0"
						      :max="warehouse.stock"
						    />
						    <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
						  </div>
						</template>
					</Table>
					</Col>
				</Row>
			</Form>
			<!-- 自定义底部按钮 -->
			<template #footer>
				<div class="custom-modal-footer">
					<Button type="primary" size="large" @click="submit">
						{{$t('page.product.submit')}}
					</Button>
				</div>
			</template>
		</Modal>

		<Modal v-model="productShow" scrollable :title="$t('page.order.add') + ' ' +$t('page.order.item')"
			:closable="true" width="70%" :footer-hide="true" :mask-closable="false">
			<Form ref="orderData" :model="productSearchsData" :label-width="labelWidth" :label-position="labelPosition"
				class="tabform" @submit.native.prevent>
				<div class="acea-row">
					<FormItem :label="$t('page.order.item')+' '+ $t('page.stock.search')+':'">
						<Input v-model="productSearchsData.store_name" placeholder="" element-id="item_name" clearable
							style="width:250px;">
						<WordCount :value="productSearchsData.store_name" :total="20" />
						</Input>
					</FormItem>
					<Button type="primary" @click="productSearchs" class="ml20">{{$t('page.order.search')}}</Button>
				</div>
			</Form>
			<div>
				<vxe-table border="inner" ref="xTable" class="mt25" :loading="loading" row-id="id" :radio-config="{
	            reserve: false,
	            checkMethod: disableCheckMethod, // 添加禁用检查方法
	            highlight: true,
				checkStrictly: true,
	          }" @checkbox-all="checkboxAll" @radio-change="radioChange" :data="productList" :row-class-name="rowClassName">
					<template #empty>
						<p class="empty-text">{{$t('page.product.no_data')}}</p>
					</template>
					<vxe-column type="radio" width="100" :check-method="disableCheckMethod"></vxe-column>
					<vxe-column field="id" :title="$t('page.order.product')+'id'" width="90"></vxe-column>
					<vxe-column field="image" :title=" $t('page.product.image')" width="70">
						<template v-slot="{ row }">
							<viewer>
								<div class="tabBox_img">
									<img v-lazy="row.image" width="100%" />
								</div>
							</viewer>
						</template>
					</vxe-column>
					<vxe-column field="store_name" :title="$t('page.order.product') + $t('page.order.name')"
						min-width="250">
						<template v-slot="{ row }">
							<Tooltip :transfer="true" theme="dark" max-width="300" :delay="600"
								:content="row.store_name">
								<div class="line2">{{ row.store_name }}</div>
							</Tooltip>
						</template>
					</vxe-column>

					<vxe-column field="price" :title="$t('page.order.product') + $t('page.order.price')" min-width="90">
						<template v-slot="{ row }">
							<div>{{ row.price.toFixed(2) }}</div>
						</template>
					</vxe-column>
					<vxe-column field="stock" :title="$t('page.stock.stock')" min-width="90"></vxe-column>
				</vxe-table>
				<div class="acea-row row-right page">
					<Page :total="total" :current="productSearchsData.page" @on-change="pageChange"
						:page-size="productSearchsData.limit" />
				</div>
			</div>

			<Button type="primary" @click="submitProduct()">{{$t('page.order.submit')}}</Button>
		</Modal>
	</div>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import {
		storeCustomerDetailApi
	} from "@/api/storeCustomer";
	import {
		createActivityProductApi
	} from '@/api/capital'
	import {
		productInfoApi,
		activityProductListInfo
	} from "@/api/product";
	export default {
		name: 'customerInfo',
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			activityId: {
				type: Number,
				default: null
			}
		},
		data() {
			return {
				loading: false,
				modal: false,
				innerVisible: false,
				productShow: false,
				total: 0,
				ids: 0,
				// goodsColumns: [{
				// 		title: "ID",
				// 		key: "id",
				// 		width: 80
				// 	},
				// 	{
				// 		title: "商品名",
				// 		key: "store_name"
				// 	},
				// 	{
				// 		title: "缩略图",
				// 		slot: "image",
					
				// 	},
				// 	{
				// 		title: "价格",
				// 		key: "price"
				// 	},
				// 	{
				// 		title: "总库存",
				// 		key: "stock"
				// 	}
				// ],
				// skuColumns: [{
				// 		title: "SKU ID",
				// 		key: "id",
				// 		width: 80
				// 	},
				// 	{
				// 		title: "规格",
				// 		key: "suk"
				// 	},
				// 	{
				// 		title: "库存",
				// 		key: "stock"
				// 	},
				// 	{
				// 		title: "原价",
				// 		key: "price"
				// 	},
				// 	{
				// 		title: "活动价",
				// 		key: "activity_price",
				// 		slot: "activity_price"
				// 	},
				// 	{
				// 		title: "活动库存",
				// 		key: "activity_stock",
				// 		slot: "activity_stock"
				// 	}
				// ],
				productSearchsData: {
					store_name: "",
					type: 1,
					activity_id:0,
					page: 1,
					limit: 15,
				},
				images: [],
				urlList: [],
				others: [],
				productList: [],
				radioProduct: {
					skuList: []
				},
				checkPidList: [],
				formDynamic: {

				},
			};
		},
		watch: {
			visible(val) {
				this.innerVisible = val
				if (val) {
					this.handleClose();
					console.log("打开弹窗, 活动ID:", this.activityId);
					// 可以用 this.activityId 去请求商品
					// this.getGoodList(this.activityId)
				}
			},
			innerVisible(val) {
				this.$emit("update:visible", val)
			},
			// 监听radioProduct变化，确保数据格式正确
			  radioProduct: {
			    handler(newVal) {
			      if (newVal.skuList) {
			        this.$nextTick(() => {
			          this.initActivityStockData();
			        });
			      }
			    },
			    deep: true,
			    immediate: true
			  }
		},
		created() {
		  // 如果已经有数据，初始化活动库存
		  if (this.radioProduct.skuList) {
		    this.initActivityStockData();
		  }
		},
		computed: {
			labelWidth() {
				return this.isMobile ? undefined : 120;
			},
			...mapState("admin/layout", ["isMobile", "menuCollapse"]),
			// 计算属性：格式化标签数据
			customerTags() {
				return this.customerData.tags || [];
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
			goodsColumns(){
				return [{
						title: "ID",
						key: "id",
						width: 80
					},
					{
						title: $t('page.product.product_name'),
						key: "store_name"
					},
					{
						title: $t('page.product.image'),
						slot: "image",
					
					},
					{
						title: $t('page.product.price'),
						key: "price"
					},
					{
						title: $t('page.stock.total_inventory'),
						key: "stock"
					}
				]
			},
			skuColumns(){
				return [{
						title: "SKU ID",
						key: "id",
						width: 80
					},
					{
						title: $t('page.product.specification'),
						key: "suk"
					},
					{
						title: $t('page.product.original_price'),
						key: "price"
					},
					{
						title: $t('page.activity.event_price_title'),
						key: "activity_price",
						slot: "activity_price"
					},
					{
						title: $t('page.stock.warehouse'),
						key: "warehouse",
						slot: "warehouse"
					},
					{
						title: $t('page.stock.stock'),
						key: "stock",
						slot: "stock"
					},
					{
						title: $t('page.activity.event_stock_title'),
						key: "activity_stock",
						slot: "activity_stock"
					}
				]
			}
		},
		methods: {
			// 初始化活动库存数据
			  initActivityStockData() {
			    if (this.radioProduct.skuList) {
			      this.radioProduct.skuList.forEach(sku => {
			        // 确保 activity_stock 是数组格式
			        if (!Array.isArray(sku.activity_stock)) {
			          // 如果 activity_stock 是数字，转换为数组
			          if (typeof sku.activity_stock === 'number') {
			            sku.activity_stock = new Array(sku.product_stock_info.length).fill(sku.activity_stock);
			          } else {
			            // 否则初始化为与仓库数量相同的数组
			            sku.activity_stock = new Array(sku.product_stock_info.length).fill(0);
			          }
			        }
			        
			        // 确保每个仓库都有对应的活动库存值
			        sku.product_stock_info.forEach((warehouse, index) => {
			          // 如果当前仓库的活动库存未定义，设置为0
			          if (sku.activity_stock[index] === undefined || sku.activity_stock[index] === null) {
			            sku.activity_stock[index] = 0;
			          }
			        });
			      });
			    }
			  },
			   // 获取活动库存显示值
			    getActivityStockValue(row, warehouseIndex) {
			      // 确保 activity_stock 是数组
			      if (!Array.isArray(row.activity_stock)) {
			        if (typeof row.activity_stock === 'number') {
			          return row.activity_stock;
			        }
			        return 0;
			      }
			      
			      // 返回对应仓库的活动库存
			      return row.activity_stock[warehouseIndex] !== undefined ? row.activity_stock[warehouseIndex] : 0;
			    },
			    
			    // 处理活动库存输入
			    handleStockInput(val, index, warehouseIndex) {
			      const numVal = parseInt(val) || 0;
			      const maxStock = this.radioProduct.skuList[index].product_stock_info[warehouseIndex].stock;
			      
			      // 限制不能超过最大库存
			      // const finalVal = Math.min(numVal, maxStock);
				  const finalVal = numVal
			      
			      // 确保 activity_stock 是数组
			      if (!Array.isArray(this.radioProduct.skuList[index].activity_stock)) {
			        this.$set(this.radioProduct.skuList[index], 'activity_stock', 
			          new Array(this.radioProduct.skuList[index].product_stock_info.length).fill(0));
			      }
			      
			      this.$set(this.radioProduct.skuList[index].activity_stock, warehouseIndex, finalVal);
			    },
				// 提交前确保数据格式正确
				  submit() {
				    // 确保所有sku的activity_stock都是数组格式
				    this.radioProduct.skuList.forEach(sku => {
				      if (!Array.isArray(sku.activity_stock)) {
				        if (typeof sku.activity_stock === 'number') {
				          // 如果是数字，转换为与仓库数量相同的数组
				          sku.activity_stock = new Array(sku.product_stock_info.length).fill(sku.activity_stock);
				        } else {
				          // 否则初始化为0数组
				          sku.activity_stock = new Array(sku.product_stock_info.length).fill(0);
				        }
				      }
				    });
				    
				    let data = {
				      product_id: this.radioProduct.id,
				      activity_id: parseInt(this.activityId),
				      sku_list: this.radioProduct.skuList,
				    }
				    
				    // 验证逻辑
				    let isValid = true;
				    this.radioProduct.skuList.forEach(item => {
				      if (Array.isArray(item.activity_stock)) {
				        item.activity_stock.forEach((stock, wIndex) => {
				          const maxStock = item.product_stock_info[wIndex].stock;
						  console.log("item", item)
						  if(item.product_stock_info[wIndex].stock > 0){
							if(stock <= 0){
						  		this.$Message.error(`${item.suk} 的活动库存不能小于0`);
						  		isValid = false;
							}
							if (stock > maxStock) {
								this.$Message.error(`${item.suk} 的活动库存不能超过可用库存`);
								isValid = false;
							}
						  }
						  
				        });
				      }
				    });
					console.log("dddd:",data)
				
				    if (isValid) {
				      createActivityProductApi(data)
				        .then((res) => {
				          this.$Message.success(res.msg);
				          this.innerVisible = false
				          this.$emit('success')
				        })
				        .catch((res) => {
				          this.$Message.error(res.msg);
				        });
				    }
				  },
				
			//分页
			pageChange(page) {
				this.productSearchsData.page = page;
				this.getProductList();
			},
			radioChange({
				row
			}) {
				console.log("选中的行：", row)
				this.radioProduct = row
				console.log("选中的行radioProduct：", this.radioProduct)
			},
			rowClassName({ row }) {
			    if (row.stock === 0 || row.is_disable === 1) {
			      return 'row-disabled';
			    }
			    return '';
			  },
			  handleClose(){
				this.radioProduct = {}
			  },
			// checkboxChange({
			// 	records,
			// 	row
			// }) {

			// 	// 检查是否尝试选择库存为0的商品
			// 	if (row.stock <= 0) {
			// 		this.$Message.error(this.$t('page.order.stock_zero_error'));
			// 		return;
			// 	}
			// 	records.forEach(item => {
			// 		this.checkPidList.push(item.id)

			// 	})
			// 	// 原始处理逻辑
			// 	this.selectProductList = records;
			// },
			checkboxAll() {
				// 获取选中当前值
				let obj2 = this.$refs.xTable.getCheckboxRecords(true);
				// 获取之前选中值
				let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
				if (this.isAll == 0 && this.checkPidList.length <= obj.length && !this.isCheckBox) {
					obj = [];
				}
				obj = obj.concat(obj2);
				let ids = [];
				obj.forEach((item) => {
					ids.push(parseInt(item.id))
				})
				this.checkPidList = ids;
				if (!obj2.length) {
					this.isCheckBox = false;
				}
			},
			// 禁用勾选方法
			disableCheckMethod({row}) {
				// 当库存为0时禁用勾选
				if(row.stock == 0 || row.is_disable == 1){
					return false;
				}else{
					return true;
				}
			},
			productSearchs() {
				this.productSearchsData.page = 1
				this.getProductList()
			},

			submitProduct() {
				this.productShow = false
			},
			//添加产品
			addProduct() {
				this.productShow = true
				this.getProductList();
			},
			getProductList() {
				this.loading = true;
				this.productList = [];
				this.productSearchsData.activity_id = this.activityId
				activityProductListInfo(this.productSearchsData).then((res) => {
					res.data.list.forEach(item => {
						let stock = 0
						let skuList = []
						item.store_product_attr_value.forEach(attrItem => {
							stock += attrItem.stock
							skuList.push({
								product_id: item.id,
								id: attrItem.id,
								image: attrItem.image,
								price: attrItem.price,
								stock: attrItem.stock,
								store_name: item.store_name,
								suk: attrItem.suk,
								sku: attrItem.code,
								product_stock_info:attrItem.product_stock_info,
								activity_price:0,
								activity_stock:0,
							})
						})
						// if(stock == 0 || fo)
						this.productList.push({
							product_id: item.id,
							id: item.id,
							image: item.image,
							price: item.price,
							stock: stock,
							store_name: item.store_name,
							skuList: skuList,
							is_disable: item.is_disable,
						})
					})
					this.total = res.data.count;
					this.loading = false;
					this.initActivityStockData(); // 初始化活动库存数据
				}).catch((err) => {
					this.loading = false;
					this.$Message.error(err.msg);
				})
			},
			handleOk() {
				this.$emit('update:modalVisible', false);
				// 处理确认逻辑
			},
			// submit() {
			// 	// 验证表单
			// 	      if (!this.validateForm()) {
			// 	        return;
			// 	      }
					  
			// 	let data = {
			// 		product_id:this.radioProduct.id,
			// 		activity_id: parseInt(this.activityId),
			// 		sku_list:this.radioProduct.skuList,
			// 	}
			// 	let tijiao = 1
			// 	this.radioProduct.skuList.forEach(item=>{
			// 		if(item.activity_stock > item.stock){
			// 			this.$Message.error("库存不足");
			// 			tijiao = 2
			// 		}
			// 	})
			// 	console.log("this.radioProduct.skuList:",this.radioProduct.skuList)
			// 	return;
			// 	if(tijiao == 1){
			// 		createActivityProductApi(data)
			// 		    .then((res) => {
			// 		        this.$Message.success(res.msg);
			// 				this.innerVisible = false
			// 				// 触发成功事件，通知父组件刷新
			// 				this.$emit('success')
			// 		    })
			// 		    .catch((res) => {
			// 		        this.modal_loading = false;
			// 		        this.$Message.error(res.msg);
			// 		    });
			// 	}
				
			// },
			getIofo(row) {
				console.log(row.id)
				this.spinShow = true;
				this.ids = row.id;
				this.title = "客户详情";
				storeCustomerDetailApi(row.id)
					.then((res) => {
						this.images = [];
						this.others = [];
						this.formDynamic = res.data.info;
						this.splitFilesByType(res.data.info.file_url)
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			closeModal() {
				this.innerVisible = false
			}
		}
	};
</script>

<style scoped>
	/* 全局样式 */
	.customer-info-modal {
		padding: 24px;
	}

	/* 统计卡片样式 */
	.stats-cards {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 16px;
		margin-bottom: 24px;
	}

	.stat-card {
		background: #ffffff;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
		border: 1px solid #ebedf0;
	}

	.stat-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
		transform: translateY(-2px);
	}

	.card-value {
		font-size: 16px;
		font-weight: 600;
		color: #1d2129;
		margin-bottom: 4px;
	}

	.card-label {
		font-size: 14px;
		color: #86909c;
	}

	/* 主要内容区域 */
	.main-content {
		display: flex;
		gap: 24px;
	}

	/* 订单历史区域 */
	.order-history {
		flex: 2;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
	}

	.section-title {
		font-size: 18px;
		font-weight: 500;
		color: #1d2129;
	}

	.order-card {
		background: #ffffff;
		border-radius: 8px;
		padding: 16px;
		margin-bottom: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		border: 1px solid #ebedf0;
		transition: all 0.3s ease;
	}

	.order-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
	}

	.order-meta {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.order-number {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	.order-date {
		font-size: 14px;
		color: #86909c;
	}

	.order-status {
		padding: 4px 8px;
		border-radius: 4px;
		font-size: 14px;
		font-weight: 500;
	}

	.status-pending {
		background: #fff7e6;
		color: #fa8c16;
	}

	.order-customer {
		font-size: 14px;
		color: #4e5969;
		margin-bottom: 12px;
	}

	.order-items {
		margin-bottom: 12px;
	}

	.order-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 0;
		border-bottom: 1px solid #f2f3f5;
	}

	.order-item:last-child {
		border-bottom: none;
	}

	.product-info {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.product-quantity {
		color: #86909c;
	}

	.product-name {
		color: #1d2129;
	}

	.product-price {
		font-weight: 500;
		color: #1d2129;
	}

	.order-total {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		gap: 8px;
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	/* 客户信息区域 */
	.customer-profile {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.profile-card {
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		border: 1px solid #ebedf0;
		transition: all 0.3s ease;
	}

	.profile-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
	}

	.card-header {
		padding: 16px;
		border-bottom: 1px solid #f2f3f5;
	}

	.card-title {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	.card-body {
		padding: 16px;
	}

	.info-row {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}

	.info-label {
		width: 140px;
		color: #86909c;
	}

	.info-value {
		color: #1d2129;
	}

	.company-name {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
		margin-bottom: 8px;
	}

	.credit-value {
		font-size: 16px;
		color: #1d2129;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.ivu-btn-ghost {
		color: #fff;
		background: #161515 !important;
	}

	.tag {
		padding: 4px 8px;
		background: #f2f3f5;
		border-radius: 4px;
		font-size: 14px;
		color: #4e5969;
	}

	.view-all-link {
		float: right;
		color: #4c4e51;
		/* 正常状态颜色 */
		cursor: pointer;
		/* 鼠标变成手型 */
		transition: color 0.2s;
		/* 添加颜色过渡效果 */
	}

	.view-all-link:hover {
		color: #000000;
		/* 悬停状态颜色 */
		text-decoration: underline;
		/* 可选：添加下划线增强交互感 */
	}
	/* 灰色不可选行样式 */
	.row-disabled {
	  background-color: #f5f5f5 !important;
	  color: #999 !important;
	  cursor: not-allowed;
	}
</style>